//
//  ImpayesController.m
//  Cabinet
//
//  Created by Florent Montsegur on 25/12/2013.
//
//

#import "ImpayesController.h"

@implementation ImpayesController

- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
        mConsultations = [[NSMutableArray alloc] init];
        mTotalImpayes = 0;
    }
    
    return self;
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView{
    return [mConsultations count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex{
    
    if( rowIndex >= [mConsultations count])
        return @"";
    
    Consultation *cons = [mConsultations objectAtIndex:rowIndex];
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"date"] == NSOrderedSame ){
        return [[cons CreationDate] descriptionWithCalendarFormat:@"%d/%m/%y" timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
    }
    
    if( [[aTableColumn identifier] caseInsensitiveCompare:@"somme"] == NSOrderedSame )
        return [cons Somme];
    
    return @"";
}

- (void) setConsultations:(NSArray*)aConsultList{
    [self emptyConsultations];
    
    // fait disparaitre les francs
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(Paye ==  0) AND (CreationDate >= %@)", [NSCalendarDate dateWithString:@"2003-01-01 00:00:00 +0000"]];
    
    NSArray *impayesLst = [aConsultList filteredArrayUsingPredicate:predicate];
    
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"CreationDate" ascending:NO];
    NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
    
    [mConsultations addObjectsFromArray:[impayesLst sortedArrayUsingDescriptors:sortDescriptors]];
    
    for(Consultation * c in impayesLst)
    {
        mTotalImpayes += [[c Somme] floatValue];
    }
}

- (Consultation*)getConsultationAtIndex:(NSInteger)aRowIndex{
    if(aRowIndex<0)
        return nil;
    
    if(aRowIndex>=[mConsultations count])
        return nil;
    
    return [mConsultations objectAtIndex:aRowIndex];
    
}

- (void) emptyConsultations {
    [mConsultations removeAllObjects];
    mTotalImpayes = 0;
}

- (float) getTotalImpayes {
    return mTotalImpayes;
}

- (void)dealloc
{
    [self emptyConsultations];
}


@end
